<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="isUpdate ? t('action.edit') : t('action.create')"
    @ok="handleSubmit"
    :okText="t('action.save')"
    defaultFullscreen
  >
    <BasicForm @register="registerForm">
      <template #itemsSlot>
        <JVxeTable
          ref="itemsTableRef"
          :columns="itemsSchema"
          toolbar
          :toolbarConfig="toolbarConfig"
          resizable
          asyncRemove
          rowNumber
          :dataSource="itemsDataSource"
          @value-change="valueChange"
        >
          <template #toolbarSuffix>
            <div style="display: flex">
              <a-button type="primary" @click="handleOpen">选择商品</a-button>
              <!-- <a-input-group compact> -->
              <a-input
                ref="spCodeRef"
                v-model:value="spCode"
                placeholder="请扫描商品编号/条形码"
                @keydown.enter="enterAddNewRow"
                style="width: calc(100% - 80px)"
              />

              <a-tooltip title="请扫描商品编号/条形码">
                <a-button type="primary" @click="enterAddNewRow">
                  <template #icon><SearchOutlined /></template>
                  录入
                </a-button>
              </a-tooltip>
              <a-button type="primary" @click="handleOpenPur">选择采购订单</a-button>
              <a-button type="primary" @click="openPageConfig">界面设置</a-button>
              <!-- </a-input-group> -->
            </div>
          </template>
          <template #tableAction="props">
            <!-- <a-divider type="vertical" /> -->
            <Popconfirm title="确定删除吗？" @confirm="onDeleteItemsRow(props)">
              <a>{{ t('action.delete') }}</a>
            </Popconfirm>
          </template>
        </JVxeTable>
      </template>
      <template #action="{ record }">
        <TableAction :actions="itemsRowAction(record)" />
      </template>
    </BasicForm>
    <template #appendFooter>
      <a-button type="primary" @click="saveAndNext" :disabled="loading">{{ t('action.saveAndNext') }}</a-button>
    </template>
  </BasicModal>

  <SkuModel @register="register" />
  <ScanModel @register="scanRegister" />
  <PurModel @register="purRegister" />
  <custom-field-modal @register="registerCustomFieldModal" />
</template>
<script lang="ts" setup>
import { provide, ref, unref } from 'vue';
import { Popconfirm } from 'ant-design-vue';
import { useI18n } from '@/hooks/web/useI18n';
import { useMessage } from '@/hooks/web/useMessage';
import { BasicForm, useForm } from '@/components/Form';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { BasicModal, useModalInner, useModal } from '@/components/Modal';
import { JVxeTableInstance } from '/@/components/jeecg/JVxeTable/types';
import { formSchema, itemsSchema } from './purchasePreBill.data';
import { saveOrUpdate, getById, deleteItemById } from './purchasePreBill.api';
import { queryByText } from '/@/views/goods/sku/sku.api';
import SkuModel from '/@/views/goods/sku/components/SkuModel.vue';
import ScanModel from '/@/views/goods/sku/components/ScanModel.vue';
import PurModel from './components/PurModel.vue';
import CustomFieldModal from '/@/views/dynamic/CustomFieldModal.vue';

defineOptions({ name: 'PurchasePreBillModal' });
const { t } = useI18n();
const { createMessage } = useMessage();
const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const loading = ref(true);
const toolbarConfig = {
  btn: ['remove'],
};

const [register, { openModal }] = useModal();
const [scanRegister, { openModal: scanOpenModal }] = useModal();
const [purRegister, { openModal: purOpenModal }] = useModal();
const [registerCustomFieldModal, { openModal:openCustomFieldModal }] = useModal();

const spCodeRef = ref(null);
const spCode = ref<string>();

const itemsTableRef = ref<JVxeTableInstance>();
const itemsDataSource = ref<any[]>([]);
const [registerForm, { getFieldsValue, setFieldsValue, resetFields, validate, getFormValue, submit }] = useForm({
  labelWidth: 120,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setModalProps({ confirmLoading: false });
  itemsDataSource.value = [];
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate) || data?.isCopy) {
    setFieldsValue({ ...data?.record });
    //回显子表数据
    const result = await getById({ id: data?.record?.id });
    itemsDataSource.value = result?.items || [];
  }
});


/**
 * 打开弹出框
 */
function handleOpen() {
  openModal(true, {
    isUpdate: false,
  });
}

 /**
   * 界面设置
   */
   function openPageConfig() {
    openCustomFieldModal(true);
  }

function itemsRowAction(record) {
  return [
    {
      label: t('action.delete'),
      onClick: handleItemsDelete.bind(null, record),
    },
  ];
}

function handleItemsDelete(record) {
  onDeleteItemsRow(record);
}

async function onDeleteItemsRow({ row }) {
  const res = await itemsTableRef.value?.removeRows(row);
  if (res && res.rows.length > 0) {
    let rowId = row.id;
    if (!rowId.startsWith('row_')) {
      //调用删除接口
      const result = await deleteItemById({ id: row.id, billNo: row.billNo });
      if (typeof result != 'boolean') {
        //删除成功,更新总金额,优惠金额,优惠后金额
        setFieldsValue({ totalAmount: result.totalAmount, discountAmount: result.discountAmount, discountLastAmount: result.discountLastAmount });
      }
    } else {
      //更新总金额,优惠金额,优惠后金额
      valueChange(null, true);
    }
    createMessage.success('删除成功');
  }
}

async function getItemsData() {
  let itemsDataValid = true;
  let itemsData: Recordable[] = [];
  if (!itemsDataValid) {
    throw { errorFields: [{ name: ['items'] }] };
  }
  itemsData = itemsTableRef.value!.getTableData();
  return itemsData;
}

/**
 * 保存并继续
 */
function saveAndNext() {
  handleSubmit(false);
}

/**
 * @param data 成功后是否关闭弹框,默认值:true
 */
async function handleSubmit(data) {
  try {
    const values = await validate();
    values.items = await getItemsData();
    if (/* !isUpdate.value &&  */ values.items) {
      values.items.map((item) => {
        item.billNo = data.billNo;
        item.createTime = '';
        item.updateTime = '';
        item.createBy = '';
        item.updateBy = '';
      });
    }
    setModalProps({ confirmLoading: true });
    await saveOrUpdate(values, isUpdate.value);
    if (data) {
      closeModal();
    } else {
      resetFields();
    }
    emit('success');
    createMessage.success(t('common.saveSuccessText'));
  } finally {
    setModalProps({ confirmLoading: false });
  }
}

const setSpCodeCursor = () => {
  setTimeout(() => {
    const cursorPosition = spCode.value?.length;
    spCodeRef.value?.focus();
    spCodeRef.value?.setSelectionRange(cursorPosition, cursorPosition);
  }, 500);
};

function insertData(rows) {
  rows.forEach((row) => {
    row.skuId = row.id;
    row.id = '';
    row.totalAmount = row.costPrice | 0;
  });
  itemsTableRef.value?.insertRows(rows);
  valueChange(null, true);
}

provide('insertData', insertData);

async function enterAddNewRow() {
  const param = { text: spCode.value, type: 'purchase' };
  const res = await queryByText(param);
  if (res.records?.length > 1) {
    scanOpenModal(true, {
      isUpdate: false,
      param,
    });
  } else {
    insertData(res.records);
  }
}

async function valueChange(e, f) {
  if (!f) {
    let { row } = e;
    row.totalAmount = (row.skuNum * row.costPrice) | 0;
  }
  let itemsData: Recordable[] = itemsTableRef.value!.getTableData();
  const totalAmount = itemsData.reduce((sum, item) => sum + (item.totalAmount | 0), 0);
  setFieldsValue({ totalAmount: totalAmount });
  let fields = await validate(['discountAmount']);
  setFieldsValue({ discountLastAmount: totalAmount - (fields.discountAmount || 0) });
  setSpCodeCursor();
}

function handleOpenPur() {
  purOpenModal(true, {
    isUpdate: false,
  });
}

async function insertDataPur(rows) {
  if (rows.length > 0) {
    const record = rows[0];
    setFieldsValue({ ...record });
    //回显子表数据
    const result = await getById({ id: record?.id });
    if (result && result.items) {
      result.items.map((item) => {
        item.skuId = item.id;
        item.id = '';
      });
    }
    itemsDataSource.value = result?.items || [];
  }
}

provide('insertDataPur', insertDataPur);
</script>

<style lang="less" scoped>
:root {
  --panel-left: 0;
  --panel-top: 0;
}
:deep(.vxe-grid .vxe-pulldown--panel) {
  position: fixed;
  // // z-index: 9999 !important;
  left: var(--panel-left);
  top: var(--panel-top);
}
.dropdown-warp {
  width: 600px;
  height: 300px;
}
</style>
